using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
using System.Text;

public partial class Pages_Voucher : System.Web.UI.Page
{
    private SqlConnection _oleConn;
    private int year = 0;
    private static string year_string = "";
    private const string DATE_INFO = "date";

    protected void Page_Load(object sender, EventArgs e)
    {
        
        string con = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
        //string con = @"Provider=SQLSql;Data Source=CSE-PC\SQLEXPRESS;User ID=sa;Initial Catalog=DB2011;Password=1234";
        StringBuilder sv = new StringBuilder(con);
        //Label1.Text = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
        //Label1.Text = Label1.Text + con;

        //Label1.Text = "test1";
        try
        {
           //$get("divScroll").scrollTop = $get("hdnScrollTop").value;
            if (!IsPostBack)
            {

                //Call the DateCokkie function so that it can get the date info from cookie
                //as soon as the page gets loded
                GetDateCookie();
                //Label1.Text = Label1.Text + "test2";
                // Set the year into current year
                DropDownListYear.SelectedValue = DateTime.Today.Year.ToString();

                // Get a voucher number for default voucher JV for the current year

                TextBox_Refn.Text = Common.GetRefn(DropDownListRefn.SelectedValue.Trim(), DropDownListYear.SelectedValue.Trim()).ToString();


                // create data table for account input 
                DataTable dtCreditAccBuffer = new DataTable();
                dtCreditAccBuffer.TableName = "dtCreditAccBuffer";
                dtCreditAccBuffer.Columns.Add("acccode", typeof(int));
                dtCreditAccBuffer.Columns.Add("acctype", typeof(int));
                dtCreditAccBuffer.Columns.Add("accname", typeof(string));
                dtCreditAccBuffer.Columns.Add("acctypename", typeof(string));
                dtCreditAccBuffer.Columns.Add("amount", typeof(float));
                dtCreditAccBuffer.Columns.Add("explain", typeof(string));

                DataTable dtDebitAccBuffer = new DataTable();
                dtDebitAccBuffer.TableName = "dtDebitAccBuffer";
                dtDebitAccBuffer.Columns.Add("acccode", typeof(int));
                dtDebitAccBuffer.Columns.Add("acctype", typeof(int));
                dtDebitAccBuffer.Columns.Add("accname", typeof(string));
                dtDebitAccBuffer.Columns.Add("acctypename", typeof(string));
                dtDebitAccBuffer.Columns.Add("amount", typeof(float));
                dtDebitAccBuffer.Columns.Add("explain", typeof(string));

                if (Session["Account Credit Entry"] != null)
                {
                    Session.Remove("Account Credit Entry");
                }
                Session.Add("Account Credit Entry", dtCreditAccBuffer);

                if (Session["Account Debit Entry"] != null)
                {
                    Session.Remove("Account Debit Entry");
                }
                Session.Add("Account Debit Entry", dtDebitAccBuffer);

            }
            else 
            {
                DataTable dtDebitAccBuffer = new DataTable();
                dtDebitAccBuffer = (DataTable)Session["Account Debit Entry"];

                GridView1.DataSource = null;
                GridView1.DataSource = dtDebitAccBuffer;
                GridView1.DataBind();

            
            }

        }
        catch (Exception ex)
        {
            this.Label1.Text = string.Empty;
            this.Label1.Text = ex.Message;
            throw;
        }
    }

    private void GetDateCookie()
    {
        try
        {
            HttpCookie myCookie = Request.Cookies[DATE_INFO];
            if (myCookie == null)
            {
                //No cookie found or cookie expired.
                //Handle the situation here, Redirect the user or simply return;
                //TO DO here
                //lblCookieMessage.Visible = true;
                //lblCookieMessage.Text = "no Cookie found!";

                return;
            }
            if (!string.IsNullOrEmpty(myCookie.Values[DATE_INFO]))
            {
                string strDate = myCookie.Values[DATE_INFO].ToString();
                TextBoxDate.Text = strDate;
                //Yes userId is found. Mission accomplished.
            }
        }
        catch (Exception)
        {
            
            throw;
        }
    }
    protected void ButtonDebit_Click(object sender, EventArgs e)
    {

        // debit button 
        try
        {

            int amount = 0;
            if (!Int32.TryParse(TextBoxAmount.Text.Trim(), out amount))
            {
                Label1.Text = "Amount not correct";
                return;
            }
            if (amount < 0)
            {
                Label1.Text = "amount not correct";
                return;
            }

            DataTable dtDebitAccBuffer = new DataTable();
            dtDebitAccBuffer = (DataTable)Session["Account Debit Entry"];

            #region If the account already exists in table do not add a new one again
            int k;


            for (k = 0; k < dtDebitAccBuffer.Rows.Count; k++)  // find if the "sales of cisheet" account already exists
            {
                if (Convert.ToInt32(dtDebitAccBuffer.Rows[k]["acctype"]) == Common.accTypeValue)
                    if (Convert.ToInt32(dtDebitAccBuffer.Rows[k]["acccode"]) == Common.accCodeValue)
                        return;
            }

            #endregion

            DataRow dr = dtDebitAccBuffer.NewRow();
            dr["acccode"] = Common.accCodeValue;
            dr["acctypename"] = Common.accTypeName;
            dr["accname"] = Common.accCodeName;
            dr["acctype"] = Common.accTypeValue;
            dr["amount"] = TextBoxAmount.Text;
            dr["explain"] = TextBoxExplain.Text;



            dtDebitAccBuffer.Rows.Add(dr);

            GridView1.DataSource = null;
            GridView1.DataSource = dtDebitAccBuffer;
            GridView1.DataBind();



            if (Session["Account Debit Entry"] != null)
            {
                Session.Remove("Account Debit Entry");
            }
            Session.Add("Account Debit Entry", dtDebitAccBuffer);

        }
        catch (Exception Ex)
        {
            Label1.Text = Ex.Message;

        }
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        //TextBox_Refn.Text = Common.GetRefn(DropDownListRefn.SelectedValue.Trim(), DropDownListYear.SelectedValue.Trim()).ToString();
        //Label1.Text = Convert.ToDateTime(TextBoxDate.Text.ToString()).Year.ToString();
        year = Convert.ToInt32(Convert.ToDateTime(TextBoxDate.Text.ToString()).Year.ToString());
        year_string = Convert.ToDateTime(TextBoxDate.Text.ToString()).Year.ToString();

        TextBox_Refn.Text = Common.GetRefn(DropDownListRefn.SelectedValue.Trim(), Convert.ToDateTime(TextBoxDate.Text.ToString()).Year.ToString()).ToString();
    }
    protected void ButtonCredit_Click(object sender, EventArgs e)
    {
        // Credit Button
        try
        {

            int amount = 0;
            if (!Int32.TryParse(TextBoxAmount.Text.Trim(), out amount))
            {
                Label1.Text = "Amount not correct";
                return;
            }
            if (amount < 0)
            {
                Label1.Text = "amount not correct";
                return;
            }

            DataTable dtCreditAccBuffer = new DataTable();
            dtCreditAccBuffer = (DataTable)Session["Account Credit Entry"];

            #region If the account already exists in table do not add a new one again
            int k;
            int found = 0;

            for (k = 0; k < dtCreditAccBuffer.Rows.Count; k++)  // find if the "sales of cisheet" account already exists
            {
                if (Convert.ToInt32(dtCreditAccBuffer.Rows[k]["acctype"]) == Common.accTypeValue)
                    if (Convert.ToInt32(dtCreditAccBuffer.Rows[k]["acccode"]) == Common.accCodeValue)
                    {
                        dtCreditAccBuffer.Rows[k]["amount"] = Convert.ToInt32(TextBoxAmount.Text);
                        found = 1;
                    }

            }

            #endregion

            if (found == 0)
            {
                DataRow dr = dtCreditAccBuffer.NewRow();
                dr["acccode"] = Common.accCodeValue;
                dr["acctypename"] = Common.accTypeName;
                dr["accname"] = Common.accCodeName;
                dr["acctype"] = Common.accTypeValue;
                dr["amount"] = Convert.ToInt32(TextBoxAmount.Text);
                dr["explain"] = TextBoxExplain.Text;
                
                dtCreditAccBuffer.Rows.Add(dr);
            }

            GridView2.DataSource = null;
            GridView2.DataSource = dtCreditAccBuffer;
            GridView2.DataBind();
            GridView2.SelectedIndex = -1;


            if (Session["Account Credit Entry"] != null)
            {
                Session.Remove("Account Credit Entry");
            }
            Session.Add("Account Credit Entry", dtCreditAccBuffer);
        }
        catch (Exception Ex)
        {
            Label1.Text = Ex.Message;

        }
    }
    protected void ButtonAmount_Click(object sender, EventArgs e)
    {
        try
        {
            int amount = 0;
           
            if (!Int32.TryParse(TextBoxAmount.Text.Trim(), out amount))
            {
                Label1.Text = "amount not correct";
                return;
            }
            if (amount < 0)
            {
                Label1.Text = "amount not correct";
                return;
            }
            if (GridView1.SelectedIndex > -1)
            {
                DataTable dtDebitAccBuffer = new DataTable();
                dtDebitAccBuffer = (DataTable)Session["Account Debit Entry"];

                
                int i = GridView1.SelectedIndex;
                dtDebitAccBuffer.Rows[i]["AMOUNT"] = amount;
                GridView1.DataSource = null;
                GridView1.DataSource = dtDebitAccBuffer;
                GridView1.DataBind();
                GridView1.SelectedIndex = -1;

                if (Session["Account Debit Entry"] != null)
                {
                    Session.Remove("Account Debit Entry");
                }
                Session.Add("Account Debit Entry", dtDebitAccBuffer);


            }
            if (GridView2.SelectedIndex > -1)
            {
                DataTable dtCreditAccBuffer = new DataTable();
                dtCreditAccBuffer = (DataTable)Session["Account Credit Entry"];

                int i = GridView2.SelectedIndex;
                dtCreditAccBuffer.Rows[i]["AMOUNT"] = amount;
                GridView2.DataSource = null;
                GridView2.DataSource = dtCreditAccBuffer;
                GridView2.DataBind();
                GridView2.SelectedIndex = -1;

                if (Session["Account Credit Entry"] != null)
                {
                    Session.Remove("Account Credit Entry");
                }
                Session.Add("Account Credit Entry", dtCreditAccBuffer);

            }
        }
        catch (Exception Ex)
        {

            Label1.Text = Ex.Message;
        }
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        // debit delete 
        try
        {

            DataTable dtDebitAccBuffer = new DataTable();
            dtDebitAccBuffer = (DataTable)Session["Account Debit Entry"];

            dtDebitAccBuffer.Rows.RemoveAt(GridView1.SelectedIndex);
            dtDebitAccBuffer.AcceptChanges();

            GridView1.DataSource = null;
            GridView1.DataSource = dtDebitAccBuffer;
            GridView1.DataBind();
            GridView1.SelectedIndex = -1;


            if (Session["Account Debit Entry"] != null)
            {
                Session.Remove("Account Debit Entry");
            }
            Session.Add("Account Debit Entry", dtDebitAccBuffer);

        }
        catch (Exception Ex)
        {
            Label1.Text = Ex.Message;
        }
    }
    protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        // Credit delete 
        try
        {

            if (GridView2.SelectedIndex > -1)
            {
                DataTable dtCreditAccBuffer = new DataTable();
                dtCreditAccBuffer = (DataTable)Session["Account Credit Entry"];

                dtCreditAccBuffer.Rows.RemoveAt(GridView2.SelectedIndex);
                dtCreditAccBuffer.AcceptChanges();

                GridView2.DataSource = null;
                GridView2.DataSource = dtCreditAccBuffer;
                GridView2.DataBind();
                GridView2.SelectedIndex = -1;



                if (Session["Account Credit Entry"] != null)
                {
                    Session.Remove("Account Credit Entry");
                }
                Session.Add("Account Credit Entry", dtCreditAccBuffer);
            }
        }
        catch (Exception Ex)
        {
            Label1.Text = Ex.Message;
        }
    }
    protected void ButtonSave_Click(object sender, EventArgs e)
    {

        
        //set the date cookie first
        HttpCookie _cookie = new HttpCookie(DATE_INFO);
        _cookie[DATE_INFO] = TextBoxDate.Text;
        _cookie.Expires = DateTime.Now.AddDays(1);
        Response.Cookies.Add(_cookie);


        Label1.Text = string.Empty;

        #region  check whether new entry is possible, logic is,
        // if the balance sheet is saved for this month, no entry is possible

        DataSet ds = new DataSet();
        //Common.Getdata(ds, "select OK from defbshit where year_code=" + year + " and month_type=" + DropDownListMonth.SelectedValue, "okvalue");
        string query = "select OK from defbshit where year_code=" + Convert.ToDateTime(TextBoxDate.Text.ToString()).Year.ToString() + " and month_type=" + Convert.ToDateTime(TextBoxDate.Text.ToString()).Month.ToString();
        Common.Getdata(ds, query, "okvalue");

        if (ds.Tables["okvalue"].Rows.Count < 1)
            Label1.Text = "Data cannot be saved in this future time";
        else if (!(ds.Tables["okvalue"].Rows[0][0] is DBNull))
                if (Convert.ToInt32(ds.Tables["okvalue"].Rows[0][0]) == 1)
                {
                Label1.Text = "Data cannot be saved in this month,year of saved balanced sheet";
                return;
                }

        #endregion

        #region Count how many accounts are there and load them to dtAccBuffer, one check
        // two checks to be done 1. check whether total debit =total credit

        DataTable dtCreditAccBuffer = new DataTable();
        DataTable dtDebitAccBuffer = new DataTable();
        dtCreditAccBuffer = (DataTable)Session["Account Credit Entry"];
        dtDebitAccBuffer = (DataTable)Session["Account Debit Entry"];
        int no_of_credit_accounts = dtCreditAccBuffer.Rows.Count;
        int no_of_Debit_accounts = dtDebitAccBuffer.Rows.Count;

        decimal total_debit = 0;
        foreach (DataRow accrow in dtCreditAccBuffer.Rows)
        {
            total_debit = total_debit + Convert.ToDecimal(accrow["amount"]);
        }
        decimal total_credit = 0;
        foreach (DataRow accrow in dtDebitAccBuffer.Rows)
        {
            total_credit = total_credit + Convert.ToDecimal(accrow["amount"]);
        }
        if (total_debit != total_credit)
        {
            Label1.Text = "Debit side is not equal to credit side";
            return;
        }
        else if (total_debit == 0)
        {
            Label1.Text = "No entry given yet";
            return;
        }
        #endregion

        #region connect to database and save each item in dtCreditAccBuffer and dtDebitAccBuffer into TRADE table

        string conString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
        
        SqlCommand myCommInsert = new SqlCommand();
        myCommInsert.Connection = new SqlConnection(conString);
        myCommInsert.Connection.Open();


        int refno;
        refno = Common.GetRefn(DropDownListRefn.SelectedValue.Trim(), Convert.ToDateTime(TextBoxDate.Text.ToString()).Year.ToString());
        string str_refno = Convert.ToString(refno);




        foreach (DataRow accrow in dtCreditAccBuffer.Rows)
        {

            string strQuery2 = "INSERT INTO [DB2011].[dbo].[TRADE]" +
                " ([NATURE],[REFN],[DATE],[TIME],[CRACCTYPE],[CREDITACC],[DEBACCTYPE],[DEBITACC],[AMOUNT],[EXPLAIN])" +
                " VALUES (" +
                "'" + DropDownListRefn.SelectedValue.ToString() + "','" + refno +
                "','" + TextBoxDate.Text.Trim() + "','" + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() +
                "','" + accrow["acctype"] + "','" + accrow["acccode"] + "'," + "null" +
                ",'" + (-1) * no_of_Debit_accounts + "','" + accrow["amount"] + "','" + accrow["explain"].ToString() + "')";

            myCommInsert.CommandText = strQuery2;
            myCommInsert.ExecuteNonQuery();
        }

        foreach (DataRow accrow in dtDebitAccBuffer.Rows)
        {

            string strQuery3 = "INSERT INTO [DB2011].[dbo].[TRADE]" +
                " ([NATURE],[REFN],[DATE],[TIME],[DEBACCTYPE],[DEBITACC],[CRACCTYPE],[CREDITACC],[AMOUNT],[EXPLAIN])" +
                " VALUES (" +
                "'" + DropDownListRefn.SelectedValue.ToString() + "','" + refno +
                "','" + TextBoxDate.Text.Trim() + "','" + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() +
                "','" + accrow["acctype"] + "','" + accrow["acccode"] + "'," + "null" +
                ",'" + (-1) * no_of_credit_accounts + "','" + accrow["amount"] + "','" + accrow["explain"].ToString() + "')";
            myCommInsert.CommandText = strQuery3;
            myCommInsert.ExecuteNonQuery();
        }
        myCommInsert.Connection.Close();
        Label1.Text = "saved successfully";
        #endregion

        ButtonSave.Enabled = false;
    }

   
}
